% Get the life time for unfolding and refolding states of 2state models
clear all;
sampling_freq=197; % sampling frequecy in herz
filename='G:\Research_Data\R1R3\20140804_his_Talin_R1_R3_bead005_800-10000s_10.7_2state_hmm';
readfile = sprintf('%s%s',filename,'.dat');
file=importdata(readfile);
hmmd_states=file.data(:,1);
currentstates=0;
startseq=1;
endseq=1;
states=[];
states1=[];
states2=[];
for i=1:1:(size(hmmd_states)-1)
    if hmmd_states(i)~= hmmd_states(i+1)
        endseq=i;
        states=[states; currentstates hmmd_states(i) startseq endseq ((endseq-startseq+1)/sampling_freq)];
        if currentstates
            states1=[states1; currentstates hmmd_states(i) startseq endseq ((endseq-startseq+1)/sampling_freq)];
        else
            states2=[states2; currentstates hmmd_states(i) startseq endseq ((endseq-startseq+1)/sampling_freq)];
        end
        startseq=i+1;
        currentstates=~currentstates;
    end
end
[mu1 delta1]=expfit(states1(:,5));
[mu2 delta2]=expfit(states2(:,5));
filename = sprintf('%s%s',filename,'-step-lifetime.dat');
fid = fopen(filename,'w');
fprintf(fid,'states\thmmvalue\tstart\tend\tlifetime(s)\n');
fprintf(fid,'%d\t%f\t%d\t%d\t%f\t\n',states');
fclose(fid);
filename = sprintf('%s%s',filename,'-step-lifetime-fit.dat');
fid = fopen(filename,'w');
fprintf(fid,'states\thmmvalue\tmu\tupper\tlower(s)\n');
fprintf(fid,'%d\t%f\t%f\t%f\t%f\n',0,states1(1,2)',1\mu1,delta1);
fprintf(fid,'%d\t%f\t%f\t%f\t%f\n',1,states2(1,2)',1\mu2,delta2);
fclose(fid);